package com.unittec.zk.provider.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;

/**
 * @description Excel工具类
 * @author Jason
 * @date 2020/01/20
 */
@Component
public class ExcelUtil {

    @Resource
    FreeMarkerConfigurer freeMarkerConfigurer;

    private static final int DAY = 36500;

    public String exportExcel(Map<String, Object> dataMap, String templateName, String fileName) {
        File file = null;
        String url = null;
        try {
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName, "UTF-8");
            file = createExcel(dataMap, template);
            FileInputStream fis = new FileInputStream(file);
            String key = "download/" + UUIDUtils.getId() + ".xls";
            OssUtils.uploadObject2Oss(key, fileName, fis);
            url = OssUtils.getUrl(key, DAY);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (file != null) {
                file.delete();
            }
        }
        return url;
    }

    private static File createExcel(Map<?, ?> dataMap, Template template) {
        String name = "temp" + OrderNumUtils.createOrderNum() + ".xls";
        File f = new File(name);
        Template t = template;
        try {
            Writer w = new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8);
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return f;
    }
}
